/*
 * @Author: wangdazhuang
 * @Date: 2024-08-21 14:23:37
 * @LastEditTime: 2025-02-20 14:19:08
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/app_prepare.dart
 */

import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart' hide Response;
import 'package:pornhub_app/components/base_refresh/base_refresh_style.dart';
import 'package:pornhub_app/env/environment_service.dart';
import 'package:pornhub_app/services/storage_service.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/conditional_future.dart';

import 'views/player/play_center_dispatch.dart';

class AppPrepare {
  AppPrepare._();

  late StreamSubscription<List<ConnectivityResult>> _connectivityStatus;

  get connectivityStatus => _connectivityStatus;

  static Future<void> init() async {
    await Get.putAsync(() => StorageService().init());

    //先检测网络状态
    if (!kIsWeb && !await _checkNetworkStatus()) {
      Environment.isHaveNetWork = false;
      return;
    }
    if (!GetPlatform.isWeb) {
      await _chooseAPILines();
    }
    _setGlobalEasyRefresh();

    if (!Environment.isChooseSuccess) return;
    await _initServices();
  }

  static Future<void> _initServices() async {
    /// 初始化StorageService 并且注册到Get 的依赖管理器中
    /// 后续在应用中,可以使用 StorageService storageService = Get.find<StorageService>()
    /// 查找到 此处初始化后的 StorageService 实例, 并进行调用

    /// 初始化,并注册用户信息到Get中.
    Get.lazyPut(() => UserService());

    Get.lazyPut(() => PlayCenterDispatch());

    /// 初始化AppService, 并且注册到Get 的依赖管理中,
    /// 后续在应用中,可以使用 AppService appService = Get.find<AppService>()
    /// 查找到 此处初始化后的 AppService 实例, 并进行调用
    // await Get.putAsync(() => AppService().init());
  }

  ///选线
  static Future<void> _chooseAPILines([List<String>? apis]) async {
    const String suffix = "sys/live";
    apis ??= Environment.apiList;
    if (apis.isEmpty) return;
    final option = BaseOptions(connectTimeout: const Duration(seconds: 15));
    final dio = Dio(option);
    final fs = apis.map((item) async {
      try {
        return await dio.get("$item/api/$suffix");
      } catch (e) {
        return Future.value(null);
      }
    }).toList();
    final storageService = Get.find<StorageService>();

    final res = await ConditionalFuture<Response?>(
      fs,
      (res) =>
          res != null &&
          res.statusCode != null &&
          res.statusCode! >= 200 &&
          res.statusCode! < 300,
    ).any();
    if (res != null) {
      final line = '${res.realUri.origin}/api/';
      Environment.androidiOSAPI = line;
      storageService.setLastSuccessDomain(line);
    } else if (Environment.backupApisJsonURL.isNotEmpty) {
      await _getBackupApisJson(dio);
    }
  }

  static _getBackupApisJson(Dio dio) async {
    final backupResponses = await Future.wait(
      Environment.backupApisJsonURL.map((item) async {
        try {
          final response = await dio.get(item);
          if (response.data != null) {
            return List<String>.from(response.data);
          }
        } catch (e) {
          return null;
        }
        return null;
      }),
    );
    // 获取并更新成功的备份 API 地址
    final backupApis = backupResponses.whereType<List<String>>().toList();
    if (backupApis.isNotEmpty) {
      await _chooseAPILines(backupApis.first);
    }
  }

  static Future<bool> _checkNetworkStatus() async {
    try {
      final List<ConnectivityResult> connectivityResult =
          await (Connectivity().checkConnectivity());
      if (!connectivityResult.contains(ConnectivityResult.none)) {
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  static void _setGlobalEasyRefresh() {
    EasyRefresh.defaultHeaderBuilder = BaseRefreshStyle.defaultHeaderBuilder;
    EasyRefresh.defaultFooterBuilder = BaseRefreshStyle.defaultFooterBuilder;
  }
}
